import type { MenuOption } from "naive-ui";
import { routerPush } from "@/utils";

export const useMenu = (menus: App.GlobalMenuOption[]) => {
  const route = useRoute();
  const expandedKeys = ref<string[]>([]);

  /** 菜单项跳转 */
  const handleMenuSelect = (_key: string, item: MenuOption) => {
    const menuItem = item as App.GlobalMenuOption;
    routerPush(menuItem.path, menuItem.newTab);
  };

  /** 深度优先搜索 当前菜单路径 */
  const getActivePathDFS = (
    activeKey: string,
    activePath: string[],
    menu?: App.GlobalMenuOption
  ) => {
    if (!menu) return false;
    if (activeKey == menu.key) return true;
    if (!menu.children) return false;
    for (const childMenu of menu.children as App.GlobalMenuOption[]) {
      if (getActivePathDFS(activeKey, activePath, childMenu)) {
        activePath.push(childMenu.key);
        return true;
      }
    }
    return false;
  };

  /** 获取当前路由所在菜单数据的paths */
  const getActiveKeyOfMenus = (
    activeKey: string,
    menus: App.GlobalMenuOption[]
  ) => {
    for (const menu of menus) {
      let keys: string[] = [];
      if (getActivePathDFS(activeKey, keys, menu)) {
        keys.push(menu.key);
        return keys;
      }
    }
    return [];
  };

  watch(
    () => route.name,
    (val) => {
      expandedKeys.value = getActiveKeyOfMenus(val as string, menus);
    },
    { immediate: true }
  );

  return {
    route,
    expandedKeys,
    handleMenuSelect,
  };
};
